//
//  GMMyselfVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/5/23.
//  Copyright © 2018年 小熊. All rights reserved.
//

#import "GMMyselfVC.h"

//Controller
#import "GMInfoController.h"
#import "GMTrainViewController.h"
#import "GMStudyViewController.h"
#import "GMPracticeViewController.h"
#import "XZCollectSourceVC.h"
#import "GMExamViewController.h"
#import "GMQuestionViewController.h"
#import "GMNotesViewController.h"
#import "XZTestDynamicVC.h"
#import "GMTodayTaskVC.h"
#import "GMAboutController.h"
#import "XZSuggestVC.h"

//Modle
#import "GMRowItem.h"
#import "GMGroupItem.h"
#import "XZInfoModel.h"

//View
#import "XZSingInView.h"
#import "XZMyselfHeaderView.h"
#import "GMMyselfViewCell.h"
#import "GMMyselfSecondCell.h"
#import "GMExercisesVC.h"

@interface GMMyselfVC ()<UITableViewDataSource,UITableViewDelegate,XZMyselfHeaderViewDelegate,XZSingInViewDelegate>
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, strong)XZSingInView *singinView;
@property (nonatomic, strong) XZMyselfHeaderView *headerView;
@property (nonatomic, strong) XZInfoModel *model;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

static NSString *MyselfViewCell = @"GMMyselfViewCell";
static NSString *MySecondCell = @"GMMyselfSecondCell";
@implementation GMMyselfVC

#pragma mark - Lifecycle
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的";
    self.view.backgroundColor = kWhiteColor;
    [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"default_icon"] action:@selector(infomation)];
    //导航栏logo
    UIImageView *img = [[UIImageView alloc]init];
    img.image = [[UIImage imageNamed:@"navIcon"]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithCustomView:img];
    self.navigationItem.leftBarButtonItem = leftBar;
}

#pragma mark - Networking && MakeData
- (void)getData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    __weak typeof(self)weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.model = nil;
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetUserInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSDictionary *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                XZInfoModel *infoModel = [XZInfoModel mj_objectWithKeyValues:dataInfo];
                self.headerView.model = infoModel;
                //这里要注意
                weakSelf.model = infoModel;
                //图片的缓存大小
                infoModel.memorySize = [weakSelf getImageCashSize];
                [weakSelf setGroupOne];
                [weakSelf setGroupTwo:infoModel];
                [weakSelf setGroupThree:infoModel];
                [weakSelf.tabView.mj_header endRefreshing];
            }else{
                /*即使失败了也要展示tableview*/
                [weakSelf setGroupOne];
                [weakSelf setGroupThree:nil];
                [weakSelf.tabView.mj_header endRefreshing];
            }
        }else{
            /*即使失败了也要展示tableview*/
            [weakSelf setGroupOne];
            [weakSelf setGroupThree:nil];
            [weakSelf.tabView.mj_header endRefreshing];
        }
    }];
}
/**第1列的数据*/
- (void) setGroupOne{
    [self.dataSource removeAllObjects];
    GMRowItem *firstItem = [GMRowItem itemWithTitle:@"培训记录" image:[UIImage imageNamed:@"me_TrainCode"]];
    

    
    GMRowItem *threeItem = [GMRowItem itemWithTitle:@"练习记录" image:[UIImage imageNamed:@"me_Practice"]];
    
    
    GMRowItem *sixItem = [GMRowItem itemWithTitle:@"我的笔记" image:[UIImage imageNamed:@"me_Mynode"]];
    
    GMRowItem *sevenItem = [GMRowItem itemWithTitle:@"收藏资源" image:[UIImage imageNamed:@"me_CollecResource"]];
    
    GMRowItem *eightItem = [GMRowItem itemWithTitle:@"收藏题目" image:[UIImage imageNamed:@"me_CollectTest"]];
    

    
    GMGroupItem *group = [[GMGroupItem alloc]init];

     group.items = @[firstItem,threeItem,sixItem,sevenItem,eightItem];
    [self.dataSource addObject:group];
}
/**第3列的数据*/
- (void)setGroupTwo:(XZInfoModel *)model{
    GMRowItem *testDynamic = [GMRowItem itemWithTitle:@"考试动态"];
    testDynamic.subTitle = [NSString stringWithFormat:@"%ld",(long)model.TestCount];
    GMGroupItem *group = [[GMGroupItem alloc]init];
    group.items = @[testDynamic];
    //当TestCount=0时隐藏考试动态
    if (model.TestCount >  0) {
       [self.dataSource addObject:group];
    }
}
/**第3列的数据*/
- (void)setGroupThree:(XZInfoModel *)model{
    GMRowItem *firstItem = [GMRowItem itemWithTitle:@"今日任务"];
    if (model != nil) {
        firstItem.subTitle = [NSString stringWithFormat:@"%ld项未完成",(long)model.NoFinishedTaskCount];
    }

    GMRowItem *secondItem = [GMRowItem itemWithTitle:@"当前版本"];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本当前版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    secondItem.subTitle = app_Version;
    
    GMRowItem *threeItem = [GMRowItem itemWithTitle:@"分享软件给好友"];
    
    GMRowItem *fourthItem = [GMRowItem itemWithTitle:@"问题建议反馈"];
    
    GMRowItem *fiveItem = [GMRowItem itemWithTitle:@"清除缓存"];
    fiveItem.subTitle = [self getImageCashSize];//缓存大小
    
    GMRowItem *sixItem = [GMRowItem itemWithTitle:@"关于我们"];
    
    GMGroupItem *group = [[GMGroupItem alloc]init];
    group.items = @[firstItem,secondItem,threeItem,fourthItem,fiveItem,sixItem];
    [self.dataSource addObject:group];
    [self.tabView reloadData];
}
/**计算图片的缓存大小*/
- (NSString *)getImageCashSize{
    float tmpSize = [[SDImageCache sharedImageCache] getSize];
    NSString *cacheSize = tmpSize/1024 >= 1024 ? [NSString stringWithFormat:@"%.1fMB",tmpSize/1024/1024] : [NSString stringWithFormat:@"%.1fKB",tmpSize/1024];
    return cacheSize;
}
- (void)getSingin{
    NSDictionary *dict= @{
                          @"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber]
                          };
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostDaySign&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                //展示的信息
                NSString *msg = [responseObject objectForKey:RESULT_NAME_Message];
                //展示签到页面  签到成功以后刷新列表
                [self.singinView show:msg];
                [weakself.dataSource removeAllObjects];
                [weakself setGroupOne];
                [weakself getData];
            }else{
                
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络错误" toView:weakself.view];
        }
    }];
}
#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    GMGroupItem *groupItem = self.dataSource[section];
    return groupItem.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        GMMyselfViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyselfViewCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        GMGroupItem *group =self.dataSource[indexPath.section];
        GMRowItem *row = group.items[indexPath.row];
        cell.item = row;
        return cell;
    }else{
        GMMyselfSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:MySecondCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        GMGroupItem *group =self.dataSource[indexPath.section];
        GMRowItem *row = group.items[indexPath.row];
        cell.item = row;
        return cell;
    }
}

#pragma mark - TableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 5)];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 1)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return AdaptedHeight(35);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.model.TestCount > 0) {
        switch (indexPath.section) {
            case 0:{
                switch (indexPath.row) {
                    case 0:{
                        //培训记录
                        GMTrainViewController *trainVC = [[GMTrainViewController alloc] init];
                        [self.navigationController pushViewController:trainVC animated:YES];
                    }
                        break;
                    case 1:{
                        //练习记录
                        GMPracticeViewController *practiveVC = [[GMPracticeViewController alloc] init];
                        [self.navigationController pushViewController:practiveVC animated:YES];
                    }
                        break;
                    case 2:{
                        //我的笔记
                        GMNotesViewController *notes = [[GMNotesViewController alloc] init];
                        [self.navigationController pushViewController:notes animated:YES];
                    }
                        break;
                    case 3:{
                        //收藏资源
                        XZCollectSourceVC *collectSourceVC = [[XZCollectSourceVC alloc]init];
                        [self.navigationController pushViewController:collectSourceVC animated:true];
                    }
                        break;
                    case 4:{
                        //收藏题目
                        GMExercisesVC *exercises = [[GMExercisesVC alloc] init];
                        exercises.fromType = @(3);
                        [self.navigationController pushViewController:exercises animated:YES];
                    }
                        break;
                    default:
                        break;
                }
            }
                break;
            case 1:{
                switch (indexPath.row) {
                    case 0:{
                        //考试动态
                        XZTestDynamicVC *testDynamicVC = [[XZTestDynamicVC alloc]init];
                        [self.navigationController pushViewController:testDynamicVC animated:true];
                    }
                        break;
                    
                    default:
                        break;
                }
            }
                break;
            case 2:{
                switch (indexPath.row) {
                    case 0:{
                        //今日任务
                        GMTodayTaskVC *today = [[GMTodayTaskVC alloc] init];
                        [self.navigationController pushViewController:today animated:YES];
                    }
                        break;
                    case 1:{
                        //检查版本更新
                        //                [MBProgressHUD showErrorOrSuc:@"检查版本更新" toView:self.view];
                    }
                        break;
                    case 2:{
                        //分享软件给好友
                        XZShareController *shareVC = [[XZShareController alloc] init];
                        shareVC.shareTitle = @"腾云教育平台";
                        shareVC.shareContent = @"腾云教育平台";
                        shareVC.shareUrl =[NSString stringWithFormat:@"%@%@%@",URL_SERVER_HEADER,URL_SOFTWARE_SHARE,[XGMArchiverTools cacheForKey:USER_UserId]];
                        shareVC.shareImgUrl = @"";
                        shareVC.type = @"软件分享";
                        [self.navigationController presentSemiViewController:shareVC withOptions:@{
                                                                                                   KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                                   KNSemiModalOptionKeys.animationDuration : @(0.6),
                                                                                                   KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                                   }];
                    }
                        break;
                    case 3:{
                        //问题建议反馈
                        XZSuggestVC *suggestVC = [[XZSuggestVC alloc]init];
                        [self.navigationController pushViewController:suggestVC animated:true];
                    }
                        break;
                    case 4:{
                        //清除缓存
                        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
                        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                            [MBProgressHUD hideHUDForView:self.view animated:YES];
                            //清除图片缓存
                            [[SDImageCache sharedImageCache]clearMemory];
                            [[SDWebImageManager sharedManager].imageCache clearMemory];
                            [[SDImageCache sharedImageCache]clearDiskOnCompletion:nil];
                            
                            
                            [MBProgressHUD showErrorOrSuc:@"清除成功" toView:self.view];
                            
                            //然后从新获取图片缓存的值
                            GMGroupItem *groupItem = self.dataSource.lastObject;
                            for (GMRowItem *rowItem in groupItem.items) {
                                if ([rowItem.title isEqualToString:@"清除缓存"]) {
                                    rowItem.subTitle = [self getImageCashSize];
                                }
                            }
                            [self.tabView reloadData];
                            
                        });
                    }
                        break;
                    case 5:{
                        //关于我们
                        GMAboutController *aboutController = [[GMAboutController alloc]init];
                        [self.navigationController pushViewController:aboutController animated:true];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
                
            default:
                break;
        }
    }else{
        switch (indexPath.section) {
            case 0:{
                switch (indexPath.row) {
                    case 0:{
                        //培训记录
                        GMTrainViewController *trainVC = [[GMTrainViewController alloc] init];
                        [self.navigationController pushViewController:trainVC animated:YES];
                    }
                        break;
                    case 1:{
                        //练习记录
                        GMPracticeViewController *practiveVC = [[GMPracticeViewController alloc] init];
                        [self.navigationController pushViewController:practiveVC animated:YES];
                    }
                        break;
                    case 2:{
                        //我的笔记
                        GMNotesViewController *notes = [[GMNotesViewController alloc] init];
                        [self.navigationController pushViewController:notes animated:YES];
                    }
                        break;
                    case 3:{
                        //收藏资源
                        XZCollectSourceVC *collectSourceVC = [[XZCollectSourceVC alloc]init];
                        [self.navigationController pushViewController:collectSourceVC animated:true];
                    }
                        break;
                    case 4:{
                        //收藏题目
                        GMExercisesVC *exercises = [[GMExercisesVC alloc] init];
                        exercises.fromType = @(3);
                        [self.navigationController pushViewController:exercises animated:YES];
                    }
                        break;
                    default:
                        break;
                }
            }
                break;
            case 1:{
                switch (indexPath.row) {
                    case 0:{
                        //今日任务
                        GMTodayTaskVC *today = [[GMTodayTaskVC alloc] init];
                        [self.navigationController pushViewController:today animated:YES];
                    }
                        break;
                    case 1:{
                        //检查版本更新
                        //                [MBProgressHUD showErrorOrSuc:@"检查版本更新" toView:self.view];
                    }
                        break;
                    case 2:{
                        //分享软件给好友
                        XZShareController *shareVC = [[XZShareController alloc] init];
                        shareVC.shareTitle = @"腾云教育平台";
                        shareVC.shareContent = @"腾云教育平台";
                        shareVC.shareUrl =[NSString stringWithFormat:@"%@%@%@",URL_SERVER_HEADER,URL_SOFTWARE_SHARE,[XGMArchiverTools cacheForKey:USER_UserId]];
                        shareVC.shareImgUrl = @"";
                        shareVC.type = @"软件分享";
                        [self.navigationController presentSemiViewController:shareVC withOptions:@{
                                                                                                   KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                                   KNSemiModalOptionKeys.animationDuration : @(0.6),
                                                                                                   KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                                   }];
                    }
                        break;
                    case 3:{
                        //问题建议反馈
                        XZSuggestVC *suggestVC = [[XZSuggestVC alloc]init];
                        [self.navigationController pushViewController:suggestVC animated:true];
                    }
                        break;
                    case 4:{
                        //清除缓存
                        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
                        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                            [MBProgressHUD hideHUDForView:self.view animated:YES];
                            //清除图片缓存
                            [[SDImageCache sharedImageCache]clearMemory];
                            [[SDWebImageManager sharedManager].imageCache clearMemory];
                            [[SDImageCache sharedImageCache]clearDiskOnCompletion:nil];
                            
                            
                            [MBProgressHUD showErrorOrSuc:@"清除成功" toView:self.view];
                            
                            //然后从新获取图片缓存的值
                            GMGroupItem *groupItem = self.dataSource.lastObject;
                            for (GMRowItem *rowItem in groupItem.items) {
                                if ([rowItem.title isEqualToString:@"清除缓存"]) {
                                    rowItem.subTitle = [self getImageCashSize];
                                }
                            }
                            [self.tabView reloadData];
                            
                        });
                    }
                        break;
                    case 5:{
                        //关于我们
                        GMAboutController *aboutController = [[GMAboutController alloc]init];
                        [self.navigationController pushViewController:aboutController animated:true];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
                
            default:
                break;
        }
    }
   
}
#pragma mark - XZMyselfHeaderViewDelegate
- (void)showSignView:(NSString *)identifier{
    if ([identifier isEqualToString:@"SIGN"]) {//签到
        [self getSingin];
    }else if ([identifier isEqualToString:@"ICON"]){//用户信息
        GMInfoController *infoController = [[GMInfoController alloc]init];
        [self.navigationController pushViewController:infoController animated:true];
    }
}
#pragma mark - XZSingInViewDelegate
- (void)sininSuccess:(XZSingInView *)view{
    if (self.singinView == view) {
        [view hide];
    }
}
#pragma mark - customAction
- (void)infomation{
    GMInfoController *infoController = [[GMInfoController alloc]init];
    [self.navigationController pushViewController:infoController animated:true];
}
#pragma mark - setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    return _dataSource;
}
- (UITableView *)tabView{
    if (!_tabView) {
        _tabView =[UITableView zj_tableViewWithSuperview:self.view delegate:self style:UITableViewStyleGrouped constraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        [_tabView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        _tabView.showsVerticalScrollIndicator = false;
        _tabView.showsHorizontalScrollIndicator = false;
        //注册cell
        [_tabView registerNib:[UINib nibWithNibName:NSStringFromClass([GMMyselfViewCell class]) bundle:nil] forCellReuseIdentifier:MyselfViewCell];
        [_tabView registerNib:[UINib nibWithNibName:NSStringFromClass([GMMyselfSecondCell class]) bundle:nil] forCellReuseIdentifier:MySecondCell];
        _tabView.tableHeaderView = self.headerView;
        _tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    }
    return _tabView;
}
- (XZMyselfHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[XZMyselfHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
        _headerView.delegate = self;
    }
    return _headerView;
}
- (XZSingInView *)singinView{
    if (!_singinView) {
        _singinView =[XZSingInView viewFromXib];
        _singinView.frame = [UIScreen mainScreen].bounds;
        _singinView.backgroundColor = [UIColor colorWithHexString:@"ECECEC" andAlpha:0.5];
        _singinView.delegate = self;
    }
    return _singinView;
}
@end
